<template>
    <div class="delet_record_container">
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :row-key="getRowKey"
            :param-prop="state.paramProp"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            @select-all="onSelectAll"
            @select="onSelect">
            <template #headerOperate>
                <div class="update">
                    <div class="left">
                        <div v-auth="'CONFIG_REMIND'" class="remind" @click="remindConfig">
                            <span>配置提醒</span>
                            <span v-show="isEnable == 1" class="open">已开启</span>
                            <span v-show="isEnable != 1" class="open">已关闭</span>
                        </div>
                    </div>
                    <div class="right">
                        <el-button v-auth="'BATCH_ASSIGN_STA'" :disabled="selectData.length == 0" @click="allot">
                            批量分配
                        </el-button>
                        <el-button v-auth="'EXP_STA'" :disabled="selectData.length == 0" @click="exportExcel">
                            导出Excel
                        </el-button>
                    </div>
                </div>
            </template>
        </ZwTable>
        <Dialog ref="dialogRef" :app-dialog="appDialog" class="dialogForm">
            <div v-show="isAllot" class="inform">
                <div class="inform_icon"></div>
                <div class="inform_text">
                    开启通知后, 选择的【成员】将会在企业微信中收到提醒通知, 同时也会在后台收到提醒通知。
                </div>
            </div>
            <div v-show="!isProgress" class="formData">
                <el-form label-width="100px" :model="formData">
                    <el-form-item v-show="isAllot" label="开通通知提醒:">
                        <div class="switch">
                            <el-switch v-model="formData.enable" class="mb-2" :active-value="1" :inactive-value="0" />
                            <span v-show="formData.enable == 1" class="text">已开启</span>
                            <span v-show="formData.enable != 1" class="text">已关闭</span>
                        </div>
                    </el-form-item>
                    <el-form-item :label="label">
                        <Member ref="member" :type="1" @submit="getDepart"></Member>
                    </el-form-item>
                    <el-form-item :label="radioLabel">
                        <el-radio-group v-show="isAllot" v-model="formData.type">
                            <el-radio :label="1">每次通知</el-radio>
                            <el-radio :label="2">
                                <div class="radio_text">
                                    每天通知一次<span class="text2">(每天早上9点推送昨日汇总)</span>

                                    <el-popover
                                        trigger="hover"
                                        placement="top"
                                        :width="380"
                                        popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;">
                                        <template #reference>
                                            <div class="radio_bg"></div>
                                        </template>
                                        <template #default>
                                            <div>
                                                当员工删除了客户时,
                                                被设置收到提醒的员工会在企业微信上接收到客易达的提醒。
                                            </div>
                                            <div :style="imgList">
                                                <img :style="imgItem" src="@/assets/image/delete/5.png" alt="" />
                                                <img :style="imgItem" src="@/assets/image/delete/6.png" alt="" />
                                            </div>
                                        </template>
                                    </el-popover>
                                </div>
                            </el-radio>
                        </el-radio-group>
                        <el-radio-group v-show="!isAllot" v-model="formData.allot">
                            <el-radio :label="2">随机分配</el-radio>
                            <el-radio :label="1">平均分配</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
            </div>

            <el-progress
                v-show="isProgress"
                style="margin: 30px 0"
                color="#FF6B00"
                :text-inside="true"
                :stroke-width="22"
                :percentage="percentage"
                status="warning" />
        </Dialog>
        <el-dialog v-model="dialogVisible" title="一键提醒" width="30%" :before-close="handleClose">
            <span style="line-height: 20px">
                <span>{{ remindInfo.manager }}</span>
            </span>
            <template #footer="scope">
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="send(scope.row)">确定发送</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'DELET_RECORD' });
</script>

<script lang="tsx" setup>
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import Dialog from './components/Dialog.vue';
import Member from './components/Member.vue';
import { getSetionId, tableH, reSize } from '@/utils/utils';
import { ElButton, ElImage, ElIcon, ElPopover } from 'element-plus';
import { Picture as IconPicture } from '@element-plus/icons-vue';
import { deepCopy } from '@/utils/helper';
import unknown from '@/assets/customer/unknown.png';
import man from '@/assets/customer/man.png';
import girl from '@/assets/customer/girl.png';
import { useStore } from '@/store';
import router from '@/router';
import { reactive, ref, computed, nextTick, onActivated } from 'vue';
import {
    batchAllots,
    batchExcl,
    getDelList,
    getConfigAlert,
    setAlert,
    remindStaff
} from '@/api/employe/staffsupervision/deletrecord';
import { ElMessage } from 'element-plus';

const member = ref();
const tableRef = ref();
const isAllot = ref(true);
const isProgress = ref(false);
const label = ref('通知接收成员:');
const radioLabel = ref('设置通知频率:');
const creators = ref();
const isChangeData = ref(1);
const percentage = ref(0);
const alert_user = ref([]);
const selectData = ref([]);
const selectIdsData = ref([]);
const allotId = ref('');
const dialogVisible = ref(false);
const isEnable = ref(0); //配置提醒0已关闭1已开启
const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);
const tabH = ref<string>('0px');

const formData = ref({
    enable: 0,
    type: 1,
    allot: 1
});
const remindInfo = ref({
    type: 1,
    name: '',
    follow_staff: '',
    manager: ''
});
const ExcelUrl = ref();
const getSelect = (val: any) => {
    selectData.value = val;
};
// 分配及批量分配
const batchAllot = (val: any, type_id: any) => {
    if (selectData.value.length <= 0) return;
    const params = {
        customer_list: selectData.value,
        work_user_list: val,
        type: type_id
    };
    //批量分配删人记录id去重
    params.customer_list = [...new Set(params.customer_list)];
    batchAllots(params)
        .then((res: any) => {
            ElMessage.success('分配成功');
            tableRef.value?.clearSelection();
        })
        .catch((e: any) => {});
};
// 导出Excel
const exportData = () => {
    if (selectIdsData.value.length <= 0) return;
    const { keyword, del_cust_time, user_id, page, page_size } = state.searchParams;
    const params = {
        keyword,
        del_cust_time,
        trace_ids: selectIdsData.value,
        // work_user_ids:selectData.value,
        page,
        page_size
    };
    batchExcl(params).then((res: any) => {
        ExcelUrl.value = res.url;
        percentage.value = 100;
    });
};
const searchOption = computed(() => {
    return [
        {
            label: '客户手机号/昵称',
            name: 'keyword',
            value: '',
            type: 'input',
            placeholder: '请输入客户手机号/昵称'
        },
        {
            label: '选择员工',
            name: 'work_user_ids',
            value: '',
            type: 'select',
            placeholder: '请选择员工',
            popperClass: 'zw-hide_select_option',
            multiple: true,
            isUserSelect: true,
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '删除客户时间',
            name: 'del_cust_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
            // 设置结束日期时间为 23:59:59，设完日期不能点击 elment-plus bug？
            // defaultTime: ['00:00:00', '23:59:59']
        }
    ];
});
const defaultParams = reactive({
    keyword: '',
    user_id: '',
    del_cust_time: []
});
const state = reactive({
    searchParams: deepCopy(defaultParams),
    paramProp: { page: '', pageSize: 'page_size' },
    searchHeight: '112px'
});
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'work_user_name',
        label: '员工姓名',
        width: 160,
        render({ row, column, index }) {
            return (
                <div class="cusInfo">
                    <div class="name">{row.work_user_name ? row.work_user_name : '--'}</div>
                    <div class="sex">
                        <img src={unknown} alt="" vShow={row.work_user_gender === 0} />
                        <img src={man} alt="" vShow={row.work_user_gender === 1} />
                        <img src={girl} alt="" vShow={row.work_user_gender === 2} />
                    </div>
                </div>
            );
        }
    },
    {
        prop: 'department',
        label: '所属部门',
        width: 200,
        render({ row, column, index }) {
            return (
                <div>
                    {row.department.map((item: any, index: number) => {
                        return (
                            <span>
                                {item.name}
                                <span vShow={row.department.length - 1 != index}>、</span>
                            </span>
                        );
                    })}
                    <span vShow={row.department.length <= 0}>--</span>
                </div>
            );
        }
    },
    {
        label: '客户信息',
        minWidth: 240,
        render({ row, column, index }) {
            const slotError = () => (
                <div class="image_slot">
                    <ElIcon>
                        <IconPicture />
                    </ElIcon>
                </div>
            );
            return (
                <div class="cusInfo">
                    <ElImage src={row.cust_avatar} fit="cover" vSlots={{ error: slotError }} class="avatar"></ElImage>
                    <div class="name">{row.cust_name}</div>
                    <div class="channel">@微信</div>
                    <div class="sex">
                        <img src={unknown} alt="" vShow={row.cust_sex === 0} />
                        <img src={man} alt="" vShow={row.cust_sex === 1} />
                        <img src={girl} alt="" v-Show={row.cust_sex === 2} />
                    </div>
                </div>
            );
        }
    },
    {
        label: '客户手机号',
        width: 170,
        render({ row, column, index }) {
            return <div>{row.cust_mobile ? row.cust_mobile : '--'}</div>;
        }
    },
    {
        label: '可联系员工',
        minWidth: 200,
        render({ row, column, index }) {
            const Default = () => (
                <div class="pop_dialog">
                    {row.follows.map((item: any, index: number) => {
                        return (
                            <span class="form-tags">
                                {item?.name}
                                <span vShow={row.follows.length - 1 != index}>、</span>
                            </span>
                        );
                    })}
                </div>
            );
            const Reference = () => (
                <div class="tag_box">
                    {row.follows.map((item: any, index: number) => {
                        return (
                            <span class="form-tags">
                                {item?.name}
                                <span vShow={row.follows.length - 1 != index}>、</span>
                            </span>
                        );
                    })}
                </div>
            );
            return (
                <div>
                    <ElPopover
                        popper-class="popGroup"
                        trigger="hover"
                        vSlots={{ reference: Reference, default: Default }}
                        width={300}
                        popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"></ElPopover>
                </div>
            );
        }
    },
    {
        label: '原因',
        width: 170,
        render({ row, column, index }) {
            return (
                <div>
                    <div vShow={row.type === 1}>员工删除</div>
                    <div vShow={row.type === 2}>客户主动删除</div>
                </div>
            );
        }
    },
    {
        label: '删人时间',
        width: 200,
        render({ row, column, index }) {
            return <div>{row.delete_time ? row.delete_time : '--'}</div>;
        }
    },
    {
        prop: 'operate',
        label: '操作',
        width: 300,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row, column, index }) {
            return (
                <div class="handle">
                    <ElButton size="small" onClick={() => allot2(row)} vAuth={'ALLOT_STA'}>
                        {row.follows.length ? '重新分配' : '分配员工'}
                    </ElButton>
                    <ElButton size="small" onClick={() => detail(row)} vAuth={'CUST_DETIL_STA'}>
                        客户详情
                    </ElButton>
                    <ElButton size="small" onClick={() => remind(row)}>
                        提醒员工
                    </ElButton>
                </div>
            );
        }
    }
];

const getRowKey = (row: any) => {
    return row.id;
};

const search = (data: any) => {
    currentParams.value = data;
    tableRef.value?.clearSelection();
    state.searchParams = deepCopy(data);
};
const reset = (v: any) => {
    tableRef.value?.clearSelection();
    state.searchParams = deepCopy(defaultParams);
    currentParams.value = null;
};
/**
 * @description: 展开收起
 */
const expandHandle = (expand: boolean) => {
    state.searchHeight = expand ? '112px' : '64px';
};

const getConfigAlert2 = async (val: boolean) => {
    const res = await getConfigAlert();
    if (res) {
        formData.value.enable = res.is_enable;
        formData.value.type = res.alert_type;
        alert_user.value = res.alert_user;
        isEnable.value = res.is_enable;
        if (member.value) {
            member.value.selectedMember = [];
        }

        if (val) {
            res.alert_user.map((item: any) => {
                item.work_user.type = 'user';
                item.work_user.check = true;
                member.value.selectedMember.push(item.work_user);
            });
        }
    }
};
// 选中表格 checkbox
const onSelect = (selection, row) => {
    selectData.value = getSetionId('cust_id', selection);
    selectIdsData.value = getSetionId('id', selection);
};
// 全选
const onSelectAll = selection => {
    selectData.value = getSetionId('cust_id', selection);
    selectIdsData.value = getSetionId('id', selection);
};
// 配置提醒
const remindConfig = () => {
    appDialog.visible = true;
    isChangeData.value = 1;
    appDialog.title = '通知提醒设置';
    getConfigAlert2(true);
};
getConfigAlert2(false);
// 导出Excel
const exportExcel = () => {
    isProgress.value = true;
    isAllot.value = false;
    appDialog.visible = true;
    appDialog.title = '导出EXCEL';
    exportData();
};
// 批量分配
const allot = () => {
    label.value = '选择员工:';
    radioLabel.value = '分配方式:';
    isAllot.value = false;
    appDialog.visible = true;
    appDialog.title = '批量分配';
    if (member.value) {
        member.value.selectedMember = [];
    }
    member.value.departVisble = true;
};
// 分配员工
const allot2 = (val: any) => {
    label.value = '选择员工:';
    radioLabel.value = '分配方式:';
    selectData.value = [val.cust_id];
    isAllot.value = false;
    appDialog.visible = true;
    isProgress.value = false;
    if (member.value) {
        member.value.selectedMember = [];
    }
    appDialog.title = val.follows.length ? '重新分配' : '分配员工';
};
// 一键提醒
const remind = (row: any) => {
    allotId.value = row.id;
    dialogVisible.value = true;
    remindInfo.value.type = row.type;
    remindInfo.value.name = row.work_user_name;
    remindInfo.value.follow_staff = row.cust_name;
    remindInfo.value.manager = row.remind_content;
};
const send = (value: any) => {
    const params = {
        trace_id: allotId.value
    };
    remindStaff(params)
        .then((res: any) => {
            dialogVisible.value = false;
            ElMessage.success('发送消息成功');
        })
        .catch((e: any) => {
            dialogVisible.value = false;
        });
};
// 获取表格高度
const getTableH = () => {
    nextTick(() => {
        const h = parseInt(tableH('.zw-table__com_table'));
        tabH.value = `${h - 56}px`;
    });
};
// 详情
const detail = (row: any) => {
    router.push(`/customer/manage/list/detail?id=${row.cust_id}&type=${row.cust_type}`);
};
const fetchApi = () => {
    // 获取文件列表
    getTableH();
    return getDelList;
};
// 弹框取消按钮
const cancelHandel = () => {
    percentage.value = 0;
    appDialog.visible = false;
    member.value.isUpload = true;
    isChangeData.value = false;
    member.value.cancelHandel();
    setTimeout(() => {
        isProgress.value = false;
        isAllot.value = true;
    }, 200);
};
// 弹框确认按钮
const submitHandel = () => {
    creators.value = member.value.submitHandel();
    appDialog.visible = false;

    if (isAllot.value) {
        const params = {
            alert_id: '',
            is_enable: formData.value.enable,
            alert_type: formData.value.type,
            work_user_ids: getSetionId('id', creators.value)
        };
        if (member.value.length != 0) {
            params.alert_id = '';
            params.work_user_ids = getSetionId('id', creators.value);
            setAlert(params)
                .then((res: any) => {
                    ElMessage.success('更新配置提醒成功');
                    //重新获取配置详情
                    getConfigAlert2(false);
                    cancelHandel();
                })
                .catch((e: any) => {
                    cancelHandel();
                });
        } else {
            setAlert(params)
                .then((res: any) => {
                    ElMessage.success('更新配置提醒成功');
                    //重新获取配置详情
                    getConfigAlert2(false);
                    cancelHandel();
                })
                .catch((e: any) => {
                    cancelHandel();
                });
        }
    } else {
        if (isProgress.value) {
            window.location = ExcelUrl.value;
            cancelHandel();
            tableRef.value?.clearSelection();
        } else {
            const userList = getSetionId('id', creators.value);
            batchAllot(userList, formData.value.allot);
            cancelHandel();
        }
    }
};
// 弹框配置
const appDialog = reactive({
    visible: false,
    title: '通知提醒设置',
    width: '800px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存',
    isInit: false, //是否重置
    isChooseDisabled: false, //重新打开传递进来的数据是否重置
    chooseArr: [] // 传递进来选中的数据
});

onActivated((val: any) => {
    tableRef.value?.clearSelection();
    state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
});
</script>
<style lang="scss" scoped>
.delet_record_container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

.update {
    // width: calc(100vw - 365px);
    width: 100%;

    // height: 56px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;

    // border: 1px solid #f9f9f9;
    // margin: 7px 0 22px;
    .left {
        display: flex;
        align-items: center;

        .checkAll {
            padding: 0 12px;
            background: #f9f9f9;
            border-radius: 1px;
            border: 1px solid #eaeaea;
            box-sizing: border-box;
        }

        .remind {
            font-size: 13px;
            color: #33302d;
            padding: 10px 12px;
            box-sizing: border-box;
            background: #f9f9f9;
            border-radius: 1px;
            border: 1px solid #eaeaea;
            cursor: pointer;

            .open {
                padding-left: 8px;
                color: #f96b02;

                &:hover {
                    color: #f98b30;
                }
            }
        }
    }

    .right {
        display: flex;
        align-items: center;
    }
}

:deep(.cusInfo) {
    display: flex;
    align-items: center;

    .avatar {
        width: 36px;
        height: 36px;
        border-radius: 4px;

        .image-slot {
            .el-icon {
                font-size: 36px;
            }
        }
    }

    .name {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        margin: 0 5px;
    }

    .channel {
        font-size: 14px;
        color: #60b900;
        margin-right: 3px;
    }

    .sex {
        width: 18px;
        height: 18px;

        img {
            width: 100%;
            height: 100%;
        }
    }
}

:deep(.tag_box) {
    display: flex;
    display: -webkit-box; //谷歌
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2; //显示几行
    overflow: hidden;

    .form-tags {
        margin: 0 10px 0 0;
    }
}

:deep(.zw-table__card-header) {
    .el-row:nth-child(2) {
        width: 100%;
    }
}
</style>
